package opl.utilities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.json.JSONObject;

public class RestServiceExecuter {

	static HttpResponse response = null;

	public synchronized static String Execute(String relativeAddress, MethodType methodType,
			String jsonData) throws Exception {
		AsyncServiceHelper asyn = new AsyncServiceHelper(relativeAddress,
				methodType, jsonData);
		response = asyn.execute().get();
		String resultString = null;
		resultString = getResult(getEntityString(response.getEntity()));

		return resultString;
	}

	private static String getEntityString(HttpEntity entity) throws Exception {
		return getStringFromStream(entity.getContent());		
	}
	
	public static String getStringFromStream(InputStream is) throws Exception{
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line);
		}
		is.close();
		return sb.toString();
	}
	
	public static String getUrlContentResultAsString(String address) throws Exception{
		InputStream stream=(InputStream)new URL(address).getContent();
		String resultString=getStringFromStream(stream);
		return getResult(resultString);
	}

	private static void checkForError(String jsonString) throws Exception {
		JSONObject jsonobj = new JSONObject(jsonString);
		String error = jsonobj.get("Error").toString();
		if (!error.equalsIgnoreCase("0")) {
			throw new Exception("Error Occured : " + error);
		}
	}
//TODO :Joy Do we need to check for JSON and all in the RestExecutor .Can't it be the responsibility of JSON serializer?
	private static String getResult(String jsonString) throws Exception {
		checkForError(jsonString);
		JSONObject jsonobj = new JSONObject(jsonString);
		return jsonobj.get("Result").toString();
	}
}
